/**
* Created with CLion.
* User:Lenovo
* Date:2023-05-18
* Time:16:39
* Description:队列
*/

#include "Queue.h"

void QueueInit(Queue *pq)
{
    assert(pq);

    pq -> pHead = NULL;
    pq -> pTail = NULL;
    pq -> size = 0;
}

void QueueDestroy(Queue *pq)
{
    assert(pq);

    QNode *cur = pq -> pHead;
    while (cur)
    {
        QNode *next = cur -> next;
        free(cur);
        cur = next;
    }

    pq -> pHead = pq -> pTail = NULL;
    pq -> size = 0;
}

void QueuePush(Queue *pq, QDataType x)
{
    assert(pq);

    QNode *newNode = (QNode *)malloc(sizeof(QNode));
    if (newNode == NULL)
    {
        perror("malloc failed");
        return;
    }
    newNode -> data = x;
    newNode -> next = NULL;

    if (pq -> pTail == NULL)
    {
        assert(pq -> pHead == NULL);

        pq -> pHead = pq -> pTail = newNode;
    }
    else
    {
        pq -> pTail -> next = newNode;
        pq -> pTail = newNode;
    }
    pq -> size++;
}

void QueuePop(Queue *pq)
{
    assert(pq);
    assert(!(QueueEmpty(pq)));

    if (pq -> pHead -> next == NULL)
    {
        // 一个节点
        free(pq -> pHead);
        pq -> pHead = pq -> pTail = NULL;
    }
    else
    {
        // 多个节点
        QNode *next = pq -> pHead -> next;
        free(pq -> pHead);
        pq -> pHead = next;
    }
    pq -> size--;
}

QDataType QueueFront(Queue *pq)
{
    assert(pq);
    assert(!(QueueEmpty(pq)));

    return pq -> pHead -> data;
}

QDataType QueueBack(Queue *pq)
{
    assert(pq);
    assert(!(QueueEmpty(pq)));

    return pq -> pTail -> data;
}

int QueueSize(Queue *pq)
{
    assert(pq);

    return pq -> size;
}

bool QueueEmpty(Queue *pq)
{
    assert(pq);

    return pq -> size == 0;
}
